package com.cloudcc.mobile.view.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.Bind;
import butterknife.OnClick;

import com.cloudcc.cloudframe.bus.DataEvent;
import com.cloudcc.cloudframe.net.ErrorInfo;
import com.cloudcc.cloudframe.net.RequestListener;
import com.cloudcc.cloudframe.util.StringUtils;
import com.cloudcc.mobile.R;
import com.cloudcc.mobile.entity.ChatUser;
import com.cloudcc.mobile.entity.CoworkerEntity;
import com.cloudcc.mobile.im.UIControl;
import com.cloudcc.mobile.manager.ContactsManager;
import com.cloudcc.mobile.manager.OrmManager;
import com.cloudcc.mobile.manager.UserManager;
import com.cloudcc.mobile.presenter.ContactPresenter;
import com.cloudcc.mobile.presenter.OtherPresenter;
import com.cloudcc.mobile.util.UrlTools;
import com.cloudcc.mobile.util.UserUtils;
import com.cloudcc.mobile.view.base.BaseFragment;
import com.cloudcc.mobile.view.dynamic.DynamicOneListActivity;
import com.cloudcc.mobile.view.main.fragment.IContactUserInfo;
import com.cloudcc.mobile.widget.CloudCCTitleBar;
import com.cloudcc.mobile.widget.CloudCCTitleBar.OnTitleBarClickListener;

/**
 * @Description: userInfoFragment
 * @author wangzhiqiang 替换chatme userInfoActivity2 等
 * @date 2015-12-16 下午10:02:15
 * 
 */
public class UserInfoFragment extends BaseFragment implements IContactUserInfo,
		OnTitleBarClickListener {

	@Bind(R.id.user_follow)
	ImageView user_follow;

	@Bind(R.id.user_logo)
	ImageView user_logo;

	@Bind(R.id.user_message)
	ImageView user_message;

	@Bind(R.id.user_name)
	TextView user_name;

	@Bind(R.id.user_company)
	TextView user_company;

	@Bind(R.id.user_attr_container)
	LinearLayout user_attr_container;

	@Bind(R.id.chat_me_liuyannum)
	TextView chat_me_liuyannum;// 留言

	@Bind(R.id.chat_me_zhushinum)
	TextView chat_me_zhushinum;// 收到回复

	@Bind(R.id.chat_me_likenum)
	TextView chat_me_likenum;// 收到的赞

	@Bind(R.id.user_email)
	TextView user_email;

	@Bind(R.id.user_phone)
	TextView user_phone;

	@Bind(R.id.user_mobile_phone)
	TextView user_mobile_phone;

	@Bind(R.id.user_address)
	TextView user_address;

	@Bind(R.id.user_dynamices)
	TextView user_dynamices;

	@Bind(R.id.headerbar)
	CloudCCTitleBar headerbar;

	private String userId;
	private ChatUser user;

	private ContactPresenter mContactPresenter;

	private boolean isFromNetWork = false;

	@Override
	public void init() {
		super.init();

		mContactPresenter = new ContactPresenter(this);

		initHeader();

		initData();

	}

	private void initHeader() {
		headerbar.setOnTitleBarClickListener(this);
		headerbar.setTitle("请稍等...");
		Bundle bundle = getArguments();
		if (bundle != null) {
			userId = bundle.getString("userId", "");
		}
		if (TextUtils.isEmpty(userId)) {
			Toast.makeText(mContext, "获取用户详情失败...", 0).show();
			getActivity().finish();
			return;
		}

	}

	/**
	 * 初始化数据
	 */
	private void initData() {
		refreshUserfromCache();
		refreshUserInfoFromNet();
	}

	/**
	 * 通过sortmode的数据库 刷新 早晚得删除
	 */
	private void refreshUserfromCache() {
		CoworkerEntity contactEntity = ContactsManager.getInstance()
				.getContactById(userId);
		if (contactEntity != null) {
			user = ContactsManager.getInstance().covert2ChatUser(contactEntity);
			refreshUIAndData();
		}
	}

	/**
	 * 刷新用户
	 */
	private void refreshUserInfoFromNet() {
		isFromNetWork = true;
		mContactPresenter.getUserInfoChatter(userId);
	}

	@Override
	public void onGettedUser(DataEvent<ChatUser> event) {
		headerbar.completeProgress();
		if (event.isError()) {
			return;
		}
		user = event.getData();
		if (isFromNetWork) {
			CoworkerEntity contactEntity = ContactsManager.covert2ContactEntity(user);
			OrmManager.getManager().getOrm().save(contactEntity);
			isFromNetWork = false;
		}
		refreshUIAndData();

	}

	@SuppressLint("NewApi")
	private void refreshUIAndData() {
		if (user == null) {
			return;
		}
		user_message.setVisibility(View.VISIBLE);
		headerbar.setTitle(user.getName());
		boolean isMe = StringUtils.equals(userId, UserManager.getManager()
				.getUser().userId);
		user_follow.setVisibility(isMe ? View.INVISIBLE : View.VISIBLE);
		user_message.setVisibility(isMe ? View.INVISIBLE : View.VISIBLE);

		refreshFollowStatus();

		// 头像 TODO

		String url = UrlTools.getTopImage(userId);
		user_logo.postInvalidate();
		UserUtils.setLogoRound(url, user_logo,
				UserUtils.getBackGroudColorByUserIdHash(userId, mContext),
				UserUtils.getNickRowName(user.getName()), mContext);
		// 容器
		user_attr_container.setVisibility(View.VISIBLE);

		chat_me_liuyannum.setText(user.getFeedandcomnum());
		chat_me_zhushinum.setText(user.getCommentednum());
		chat_me_likenum.setText(user.getPraisenum());

		// 关于
		user_name.setText(user.getName());
		user_company.setText(user.getEmail());
		user_email.setText(user.getEmail());
		user_phone.setText(user.getPhone());
		user_mobile_phone.setText(user.getMobile());
		user_address.setText(user.getAddress());

		// 关于我
		user_dynamices.setEnabled(true);

	}

	private void refreshFollowStatus() {
		if (user != null) {
			user_follow
					.setImageResource(user.isIsfollowme() ? R.drawable.guanzhut
							: R.drawable.guanzhuf);
		}

	}

	/**
	 * 点击聊天
	 */
	@OnClick(R.id.user_message)
	public void clickChat() {
		if (user != null) {
			UIControl.openChatUI(mContext,ContactsManager.getInstance().encodeHXuserName(userId),
					user.getName(), false);
		}
	}

	/**
	 * 点击关注
	 */
	@OnClick(R.id.user_follow)
	public void clickFollow() {
		createWainting();
		new OtherPresenter().followPeople(userId, user.isIsfollowme(),
				new RequestListener() {

					@Override
					public void onSuccess(Object arg0) {
						dismissWainting();
						user.setIsfollowme(!user.isIsfollowme());
						refreshFollowStatus();
					}

					@Override
					public void onFailure(ErrorInfo arg0) {
						dismissWainting();
					}
				});
	}

	@OnClick(R.id.user_dynamices)
	public void clickDynamices() {
		if (user == null) {
			return;
		}
		Intent intent = new Intent(mContext, DynamicOneListActivity.class);
		intent.putExtra("userName", user.getName());
		intent.putExtra("userId", TextUtils.isEmpty(userId)?user.getUserid():userId);
		mContext.startActivity(intent);

	}

	@Override
	public int getLayoutId() {
		return R.layout.act_userinfo;
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onClickLeft(View v) {
		getActivity().finish();
	}

	@Override
	public void onClickRight(View v) {

	}

}
